//
//  SYQRCodeViewController.m
//  SYQRCodeDemo
//
//  Created by sunbb on 15-1-9.
//  Copyright (c) 2015年 SY. All rights reserved.
//

#import "SYQRCodeViewController.h"
#import "ZBarSDK.h"
#import <AVFoundation/AVFoundation.h>

//设备宽/高/坐标
#define kDeviceWidth [UIScreen mainScreen].bounds.size.width
#define KDeviceHeight [UIScreen mainScreen].bounds.size.height
#define KDeviceFrame [UIScreen mainScreen].bounds

//static const float kLineMinY = 185;
//static const float kLineMaxY = 335;
//static const float kReaderViewWidth = 150;
//static const float kReaderViewHeight = 150;



@interface SYQRCodeViewController () <AVCaptureMetadataOutputObjectsDelegate>{
    BOOL isOrientationLandscapeRight;
}

@property (nonatomic, strong) ZBarReaderView *readerView;

@property (weak, nonatomic) IBOutlet UIView *scanView;
@property (nonatomic, strong) AVCaptureSession *qrSession;//回话
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *qrVideoPreviewLayer;//读取
@property (nonatomic, strong) UIImageView *line;//交互线
@property (nonatomic, strong) NSTimer *lineTimer;//交互线控制


@end

@implementation SYQRCodeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view.
//    [self initUI];
        self.readerView.frame = self.view.bounds;
    [self.view insertSubview:self.readerView atIndex:0];
     self.readerView.scanCrop = CGRectMake(self.scanView.x/self.readerView.width,self.scanView.y/self.readerView.height,self.scanView.width/self.readerView.width,self.scanView.height/self.readerView.height);
    isOrientationLandscapeRight=[[UIApplication sharedApplication] statusBarOrientation] ==UIInterfaceOrientationLandscapeRight?YES:NO;
    [self startSYQRCodeReading];
    [self initTitleView];
    [self createBackBtn];
}

-(void)viewDidAppear:(BOOL)animated{
    //设置预览图层
    [self setOverlayPickerView];
}
- (ZBarReaderView *)readerView
{
    if (!_readerView)
    {
        _readerView = [[ZBarReaderView alloc] init];
        [_readerView willRotateToInterfaceOrientation:[[UIApplication sharedApplication] statusBarOrientation]   duration:[[UIApplication sharedApplication]statusBarOrientationAnimationDuration]];
        _readerView.readerDelegate = self;
        
        _readerView.maxZoom = 4;
    }
    return _readerView;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                         duration:(NSTimeInterval)duration
{
//    [self.readerView willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    if (UIDeviceOrientationLandscapeLeft == toInterfaceOrientation) {
        //Rotate 90
        self.readerView.transform = CGAffineTransformMakeRotation (isOrientationLandscapeRight?0:2*M_PI/2.0);
    } else if (UIDeviceOrientationLandscapeRight == toInterfaceOrientation) {
        //Rotate 270
        self.readerView.transform = CGAffineTransformMakeRotation (isOrientationLandscapeRight?-2*M_PI/2.0:0);
    }
    
}
- (void)dealloc
{
    if (_qrSession) {
        [_qrSession stopRunning];
        _qrSession = nil;
    }
    
    if (_qrVideoPreviewLayer) {
        _qrVideoPreviewLayer = nil;
    }
    
    if (_line) {
        _line = nil;
    }
    
    if (_lineTimer)
    {
        [_lineTimer invalidate];
        _lineTimer = nil;
    }
}

- (void)initTitleView
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0,0,kDeviceWidth, 64)];
    bgView.backgroundColor = TitleColor_Dark;
    [self.view addSubview:bgView];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake((kDeviceWidth - 100) / 2.0, 32, 100, 20)];
    //scanCropView.image=[UIImage imageNamed:@""];
    //titleLab.layer.borderColor = [UIColor greenColor].CGColor;
//    //titleLab.layer.borderWidth = 2.0;
//    //titleLab.backgroundColor = [UIColor colorWithRed:62.0/255 green:199.0/255 blue:153.0/255 alpha:1.0];
    titleLab.text = @"扫描";
//    titleLab.shadowColor = [UIColor lightGrayColor];
//    titleLab.shadowOffset = CGSizeMake(0, - 1);
    titleLab.font = [UIFont boldSystemFontOfSize:18.0];
    titleLab.textColor = [UIColor whiteColor];
    titleLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLab];
}

- (void)createBackBtn
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(24, 28, 20, 20)];
    [btn setImage:[UIImage imageNamed:@"back_item"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(cancleSYQRCodeReading) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void)initUI
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //摄像头判断
    NSError *error = nil;
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    if (error)
    {
        return;
    }
    
    //设置输出(Metadata元数据)
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];

    //设置输出的代理
    //使用主线程队列，相应比较同步，使用其他队列，相应不同步，容易让用户产生不好的体验
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

//    output.rectOfInterest = CGRectMake(0.5, 0.2, 0.7, 0.6);

    //拍摄会话
       self.qrSession = [[AVCaptureSession alloc] init];
        [ self.qrSession setSessionPreset:AVCaptureSessionPreset1920x1080];
        [ self.qrSession addInput:input];
        [ self.qrSession addOutput:output];
    //设置输出的格式
    //一定要先设置会话的输出为output之后，再指定输出的元数据类型
//       output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode];
    
#pragma mark 修改识别类型
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode]];

    //设置预览图层
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession: self.qrSession];

    [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
//    preview.frame =  CGRectMake(35, self.view.centerY, ScreenWidth - 70, 100);//
    preview.frame=self.view.layer.bounds;
    preview.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight|AVCaptureVideoOrientationLandscapeLeft;
    
    [self.view.layer insertSublayer:preview atIndex:0];
    self.qrVideoPreviewLayer = preview;

}

- (CGRect)getReaderViewBoundsWithSize:(CGSize)asize
{
    
    return CGRectMake(self.scanView.frame.origin.x / ScreenWidth , asize.height / ScreenHeight, asize.width / ScreenWidth, self.scanView.frame.origin.y);
   
}

- (void)setOverlayPickerView
{
    //画中间的基准线
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(self.scanView.frame.origin.x, self.scanView.frame.origin.y, self.scanView.frame.size.width, 3)];
    [_line setImage:[UIImage imageNamed:@"img_line"]];
    [self.view addSubview:_line];
    
}


#pragma mark -
#pragma mark 输出代理方法

//此方法是在识别到QRCode，并且完成转换
//如果QRCode的内容越大，转换需要的时间就越长
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //扫描结果
    if (metadataObjects.count > 0)
    {
        [self stopSYQRCodeReading];
        
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        
        if (obj.stringValue && ![obj.stringValue isEqualToString:@""] && obj.stringValue.length > 0)
        {
            
                           if (self.SYQRCodeSuncessBlock) {
                    self.SYQRCodeSuncessBlock(self,obj.stringValue);
                }
            
        }
        else
        {
            if (self.SYQRCodeFailBlock) {
                self.SYQRCodeFailBlock(self);
            }
        }
    }
    else
    {
        if (self.SYQRCodeFailBlock) {
            self.SYQRCodeFailBlock(self);
        }
       
    }
}
- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image
{
    ZBarSymbol *symbol = nil;
     [self stopSYQRCodeReading];
    for (symbol in symbols)
    {
        break;
    }
    
    NSString *zbarString = symbol.data;
    //扫描结果
    if (!IsStrEmpty(zbarString))
    {
            if (self.SYQRCodeSuncessBlock) {
                self.SYQRCodeSuncessBlock(self,zbarString);
            }
    }
    else
    {
//        if (self.SYQRCodeFailBlock) {
//            self.SYQRCodeFailBlock(self);
//        }
        UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"扫描失败，请重新扫描" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self startSYQRCodeReading];
        }];
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}

#pragma mark -
#pragma mark 交互事件

- (void)startSYQRCodeReading
{
    _lineTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 20 target:self selector:@selector(animationLine) userInfo:nil repeats:YES];
//
//    [self.qrSession startRunning];
//
//    
       [self.readerView start];
}

- (void)stopSYQRCodeReading
{
    [self.readerView stop];
    if (_lineTimer)
    {
        [_lineTimer invalidate];
        _lineTimer = nil;
    }
//
//    [self.qrSession stopRunning];
//
}

//取消扫描
- (void)cancleSYQRCodeReading
{
    [self stopSYQRCodeReading];
    
    if (self.SYQRCodeCancleBlock)
    {
        self.SYQRCodeCancleBlock(self);
    }
}


#pragma mark -
#pragma mark 上下滚动交互线

- (void)animationLine
{
    __block CGRect frame = _line.frame;
    
    static BOOL flag = YES;
    
    if (flag)
    {
        frame.origin.y = self.scanView.frame.origin.y;
        flag = NO;
        
        [UIView animateWithDuration:1.0 / 20 animations:^{
            
            frame.origin.y += 5;
            _line.frame = frame;
            
        } completion:nil];
    }
    else
    {
        if (_line.frame.origin.y >= self.scanView.frame.origin.y)
        {
            if (_line.frame.origin.y >= (self.scanView.frame.origin.y+self.scanView.frame.size.height-5))
            {
                frame.origin.y = self.scanView.frame.origin.y;
                _line.frame = frame;
                
                flag = YES;
            }
            else
            {
                [UIView animateWithDuration:1.0 / 20 animations:^{
                    
                    frame.origin.y += 5;
                    _line.frame = frame;
                    
                } completion:nil];
            }
        }
        else
        {
            flag = !flag;
        }
    }
    
}

@end
